package com.mengma.ec.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.mengma.ec.commons.Const;
import com.mengma.ec.commons.ControllerCommons;
import com.mengma.ec.commons.ServerResponse;
import com.mengma.ec.entity.Order;
import com.mengma.ec.entity.User;
import com.mengma.ec.service.portal.IOrderService;
import com.mengma.ec.vo.CartVo;
import com.mengma.ec.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.table.TableModel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xixi
 * @Date: 2018/9/26 14:46
 * @Description:
 */
@RequestMapping("/order/")
@RestController
public class OrderController {

    @Autowired
    private IOrderService iOrderService;

    // 1.创建订单
    @PostMapping("create.do")
    public ServerResponse<OrderVo> create(Integer shippingId, HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("脑子是个好东西！请先登录！");
        }
        ServerResponse<OrderVo> response = iOrderService.create(user.getId(), shippingId);
        return response;
    }

    // 2.获取订单的商品信息
    @GetMapping("get_order_cart_product.do")
    public ServerResponse get_order_cart_product(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("脑子是个好东西！请先登录！");
        }
        ServerResponse response = iOrderService.get_order_cart_product(user.getId());
        return response;
    }

    @GetMapping("list.do")
    public ServerResponse list(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("脑子是个好东西！请先登录！");
        }
        ServerResponse response = iOrderService.list(user.getId(), pageNum, pageSize);
        return response;
    }

    @GetMapping("pay.do")
    public ServerResponse<Map<String, String>> pay(Long orderNo, HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("脑子是个好东西！请先登录！");
        }
        ServerResponse response = iOrderService.pay(user.getId(), orderNo);
        return response;
    }


    @PostMapping("query_order_pay_status.do")
    public ServerResponse query_order_pay_status(Long orderNo, HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("脑子是个好东西！请先登录！");
        }
        ServerResponse response = iOrderService.query_order_pay_status(user.getId(), orderNo);
//        if(response.isSuccess()){
//            return ServerResponse.createBySuccess(true);
//        }
//        return ServerResponse.createBySuccess(false);
        return response;
    }


    /**
     * 支付宝产生回调时，把所有需要返回的数据设置在request的对象中
     *
     * @param request
     * @return
     */
    @PostMapping("alipay_callback.do")
    public Object alipay_callback(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        //拿取request中参数列（map）
        Map parameterMap = request.getParameterMap();

        //转换为我们需要的map
        for (Iterator iter = parameterMap.keySet().iterator(); iter.hasNext(); ) {
            //拿取key
            String name = (String) iter.next();

            //拿取values
            String[] values_array = (String[]) parameterMap.get(name);
            //最终需要的value
            String value = "";

            //将values数据拼凑成一个string（通过“，”分离）
            for (int i = 0; i < values_array.length; i++) {
                //三元运算符
                value = (i == values_array.length - 1)
                        ? value + values_array[i]
                        : value + values_array[i] + ",";
            }
            //将拼接好的值设置到最终需要的map中
            params.put(name, value);
        }
        try {
            params.remove("sign_type");

            boolean rsaCheckV2 = AlipaySignature.rsaCheckV2(params,Configs.getAlipayPublicKey(),
                    "utf-8",Configs.getSignType());

            if (!rsaCheckV2) {
                return ServerResponse.createByErrorMessage("乱请求！！！");
            }

            //AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());

            //记录支付成功到我们的数据库表
            //验证合法数据
            ServerResponse response = iOrderService.checkDataLegal(params);
            if (response.isSuccess()) {
                return "success";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failed";
    }


}